var express = require('express');
var app = express();
var fs = require('fs');

// get|post
var apiRouter = express.Router();
apiRouter.route("/api/:name/").get(serveRequest).post(serveRequest);
app.use(apiRouter);

function serveRequest(req, resp) {
	var api = req.params.name;
	var fileName = api + '.txt';
	fs.readFile(fileName, 'utf-8', function(err, data){
		if(err){
			resp.end('{"error":-1, "message":"invalid api"}');
		}else{
			var pageIndex = req.query.pageIndex;
			var pageSize = req.query.pageSize;
			if((null == pageIndex) && (null == pageSize)){
				var result = {
					error: 0,
					message: "success",
					data: JSON.parse(data),
				};
				return resp.end(JSON.stringify(result));
			}
			if(null == pageIndex){
				pageIndex = 1;
			}
			if(null == pageSize){
				pageSize = 20;
			}
			var arr = JSON.parse(data);
			pageIndex = parseInt(pageIndex);
			if(pageIndex<1)
				pageIndex = 1;
			pageSize = parseInt(pageSize);
			if(pageSize == 0) 
				pageSize = 10;
			if (arr.length < (pageIndex - 1) * pageSize) {
				resp.end('{"error":1, "message":"no data"}');
			}
			var newArr = [];
			for(var i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize && i < arr.length; i++){
				newArr.push(arr[i]);
			}
			var result = {
				error: 0,
				message: "success",
				data: newArr,
				dataCount: arr.length,
			};
			resp.end(JSON.stringify(result));
		}
	});
}

app.listen(3000, function(){
});
